﻿<###################################################################################################################################
 #	SERVICE			DEFAULT			NAMED
 #	SQLServer		MSSQLServer		MSSQL$<InstanceName>
 #	SQLAgent		SQLServerAgent	SQLAgent$<InstanceName>
 #	ReportServer	ReportServer	ReportServer$<InstanceName>
 #>

function Set-SQLServiceAccounts {[CmdletBinding()] param (
	[Parameter (Mandatory= $True , ValueFromPipeline= $True )][PSCustomObject]$Manifest,
	[Parameter (Mandatory= $False, ValueFromPipeline= $False)][string]$Domain=$ENV:UserDomain)

    BEGIN {[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SQLServer.SQLWMIManagement')};

    PROCESS {
        $ServerInstance= $_.Instance;
        $Account= "$Domain\$($_.Account)";
        $Password= $_.Password;
        Write-Verbose $ServerInstance;
        Write-Verbose $Account;

        if ($ServerInstance.Contains('\')) {
            $ComputerName= [string]$ServerInstance.Split('\')[0];
            $InstanceName= [string]$ServerInstance.Split('\')[1];

            $MSSQLServer= "MSSQL`$$InstanceName";
            $SQLServerAgent= "SQLAgent`$$InstanceName";
            $ReportServer= "ReportServer`$$InstanceName";
            $MSSQLServerOLAPService= "MSOLAP`$$InstanceName";
        } else {
            $ComputerName= $ServerInstance;
            $InstanceName= 'MSSQLServer';
            $InstanceName= $null;

            $MSSQLServer= 'MSSQLServer';
            $SQLServerAgent= 'SQLServerAgent';
            $ReportServer= 'ReportServer';
            $MSSQLServerOLAPService= 'MSSQLServerOLAPService';
        };
        $ReportServer= $null;

        $SQLConfigMgr= New-Object ('Microsoft.SQLServer.Management.SMO.WMI.ManagedComputer') $ComputerName;
        $SQLConfigMgr.Services | ? {$_.Name -in $MSSQLServer,$SQLServerAgent,$MSSQLServerOLAPService} | % {Write-Verbose $_.Name; $_.SetServiceAccount($Account, $Password)};
        $SQLConfigMgr.Services.Refresh();
        $SQLConfigMgr.Services | ? {$_.StartMode -eq 'Auto' -and $_.ServiceState -eq 'Stopped'} | % {$_.Start()};
    };

    END {};
};